<template>
  <view class="search">
    <view class="fixed-header">
      <view class="search-box">
        <input
          type="text"
          v-model="searchText"
          placeholder="Search"
          @confirm="handleSearch"
        />
        <button @tap="handleSearch" class="search-button">
          <img
            class="search-icon"
            src="/static/search/search-white.png"
            alt="搜索"
          />
        </button>
      </view>

      <scroll-view
        v-if="!showCategoryPopup && !searchText"
        class="category-nav"
        scroll-x="true"
        show-scrollbar="false"
      >
        <view
          class="nav-item"
          v-for="(category, index) in categories"
          :key="index"
        >
          <view
            class="nav-content"
            @tap="handleCategoryClick(category)"
            :class="{ active: isActiveCategory(category) }"
          >
            {{ category.categoryName }}
          </view>
        </view>
      </scroll-view>
      <view
        v-if="categories.length > 0 && !searchText"
        class="category-nav-down"
        @tap="showAllCategories"
      >
        <img
          class="category-nav-down-icon"
          src="/static/search/chevron-down.png"
          alt="down"
        />
      </view>
      <!-- 多级分类选择器弹窗 -->
      <view class="category-popup" v-if="showCategoryPopup" @tap.stop>
        <view class="popup-header" @tap="showAllCategories">
          <text>Select Category</text>
        </view>
        <view class="category-columns">
          <!-- 一级分类 -->
          <scroll-view class="category-column" scroll-y>
            <view
              class="category-item"
              v-for="category in categories"
              :key="category.categoryId"
              :class="{ active: selectedLevel1 === category }"
              @tap="selectLevel1(category)"
            >
              <text>{{ category.categoryName }}</text>
              <!-- <text class="count" v-if="category.children?.length">({{ category.children.length }})</text> -->
              <text class="arrow" v-if="category.children?.length">›</text>
            </view>
          </scroll-view>
          <!-- 二级分类 -->
          <scroll-view class="category-column" scroll-y v-if="selectedLevel1">
            <view
              class="category-item"
              v-for="category in selectedLevel1.children"
              :key="category.categoryId"
              :class="{ active: selectedLevel2 === category }"
              @tap="selectLevel2(category)"
            >
              <text>{{ category.categoryName }}</text>
              <!-- <text class="count" v-if="category.children?.length">({{ category.children.length }})</text> -->
              <text class="arrow" v-if="category.children?.length">›</text>
            </view>
          </scroll-view>
          <!-- 三级分类 -->
          <scroll-view
            class="category-column"
            scroll-y
            v-if="selectedLevel2 && selectedLevel2.children.length > 0"
          >
            <view
              class="category-item"
              v-for="category in selectedLevel2.children"
              :key="category.categoryId"
              :class="{ active: selectedLevel3 === category }"
              @tap="selectLevel3(category)"
            >
              <text>{{ category.categoryName }}</text>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>

    <scroll-view class="scrollable-content" scroll-y="true">
      <view class="search-result" v-if="searchText || currentCategory">
        <view class="product-grid">
          <ProductCard
            v-for="(item, index) in searchResults"
            :key="index"
            :product="item"
          />
        </view>
      </view>
      <view class="loading" v-if="loading">Loading...</view>
      <view class="loading" v-if="!loading && searchResults.length === 0"
        >No data</view
      >
    </scroll-view>
  </view>
</template>

<script>
import ProductCard from "@/components/ProductCard.vue";
import request from "@/config/request";

export default {
  components: {
    ProductCard,
  },
  data() {
    return {
      searchText: "",
      currentCategory: null,
      currentCategoryName: null,
      categories: [],
      showCategoryPopup: false,
      selectedLevel1: null,
      selectedLevel2: null,
      selectedLevel3: null,
      searchResults: [],
      loading: false,
      selectedCategoryPath: [],
      searchTimer: null,
    };
  },
  watch: {
    searchText: {
      handler(newVal) {
        if (this.searchTimer) {
          clearTimeout(this.searchTimer);
        }
        this.searchTimer = setTimeout(() => {
          if (newVal) {
            this.handleSearch();
          } else {
            this.searchResults = [];
            this.fetchProductsByCategory(this.currentCategoryName);
          }
        }, 300);
      },
      immediate: true,
    },
  },
  methods: {
    async handleSearch() {
      if (!this.searchText) return;
      try {
        this.loading = true;
        this.searchResults = [];
        const data = await request({
          url: "/api/products/search",
          method: "GET",
          data: {
            keyword: this.searchText,
          },
        });
        this.searchResults = data?.content || [];
      } catch (error) {
        console.error("搜索商品失败：", error);
        uni.showToast({
          title: "搜索失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
    async fetchCategories() {
      try {
        this.loading = true;
        const data = await request({
          url: "/api/categories/tree",
          method: "GET",
        });
        this.categories = data;
        if (this.categories.length > 0) {
          this.handleCategoryClick(this.categories[0]);
        }
      } catch (error) {
        this.loading = false;
        console.error("获取分类失败：", error);
      }
    },
    async fetchProductsByCategory(categoryName) {
      try {
        this.loading = true;
        this.searchResults = [];
        const data = await request({
          url: "/api/products/by-category",
          method: "GET",
          data: {
            category: categoryName,
          },
        });
        this.searchResults = data;
      } catch (error) {
        console.error("获取分类商品失败：", error);
        uni.showToast({
          title: "获取商品失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
    async handleCategoryClick(category) {
      this.currentCategory = category.categoryId;
      this.currentCategoryName = category.categoryName;
      this.selectedCategoryPath = [category.categoryId];
      await this.fetchProductsByCategory(category.categoryName);
    },
    showAllCategories() {
      this.showCategoryPopup = !this.showCategoryPopup;
    },
    selectLevel1(category) {
      this.selectedLevel1 = category;
      this.selectedLevel2 = null;
      this.selectedLevel3 = null;
      this.updateSelectedCategoryPath();
    },
    selectLevel2(category) {
      this.selectedLevel2 = category;
      this.selectedLevel3 = null;
      this.updateSelectedCategoryPath();
      if (!category.children || category.children.length === 0) {
        this.handleCategorySelect(category);
      }
    },
    selectLevel3(category) {
      this.selectedLevel3 = category;
      this.updateSelectedCategoryPath();
      this.handleCategorySelect(category);
    },
    handleCategorySelect(category) {
      this.currentCategory = category.categoryId;
      this.currentCategoryName = category.categoryName;
      this.updateSelectedCategoryPath();
      this.closeCategoryPopup();
      this.fetchProductsByCategory(category.categoryName);
    },
    updateSelectedCategoryPath() {
      this.selectedCategoryPath = [];
      if (this.selectedLevel1) {
        this.selectedCategoryPath.push(this.selectedLevel1.categoryId);
      }
      if (this.selectedLevel2) {
        this.selectedCategoryPath.push(this.selectedLevel2.categoryId);
      }
      if (this.selectedLevel3) {
        this.selectedCategoryPath.push(this.selectedLevel3.categoryId);
      }
    },
    isActiveCategory(category) {
      return (
        this.selectedCategoryPath.includes(category.categoryId) ||
        this.currentCategory === category.categoryId
      );
    },
    closeCategoryPopup() {
      this.showCategoryPopup = false;
    },
    getCategoryCount(category) {
      // 计算分类下的所有子分类数量
      let count = 0;
      const countChildren = (cat) => {
        count += cat.children.length;
        cat.children.forEach((child) => countChildren(child));
      };
      countChildren(category);
      return count;
    },
  },
  onLoad() {
    this.fetchCategories();
  },
};
</script>

<style lang="scss">
.search {
  height: calc(100vh - 96rpx);
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #fff8e1 0%, #ffffff 100%);
  overflow: hidden;
  box-sizing: border-box;
  padding-top: var(--status-bar-height);
  /* #ifdef MP-WEIXIN */
  height: 100vh;
  padding-top: calc(var(--status-bar-height) + 110rpx);
  /* #endif */

  .fixed-header {
    // background-color: #fff;
    position: relative;
    z-index: 1;

    .search-box {
      // background-color: #fff;
      padding: 20rpx;
      position: relative;

      input {
        flex: 1;
        height: 72rpx;
        padding: 0 120rpx 0 20rpx;
        border: 4rpx solid #000;
        border-radius: 36rpx;
        background-color: #fff;
      }

      .search-button {
        position: absolute;
        top: 30rpx;
        right: 30rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 36rpx;
        background-color: #000;
        border-radius: 36rpx;

        .search-icon {
          width: 32rpx;
          height: 32rpx;
        }
      }
    }

    .category-nav {
      // background-color: #fff;
      width: 100%;
      white-space: nowrap;
      padding: 0 80rpx 0 20rpx;
      border-bottom: 2rpx solid #f5f5f5;
      box-sizing: border-box;
      position: relative;

      ::-webkit-scrollbar {
        display: none;
      }

      .nav-item {
        display: inline-flex;
        align-items: center;
        padding: 20rpx 0rpx;
        margin-right: 20rpx;
        font-size: 28rpx;
        color: #666;

        .nav-content {
          position: relative;
          padding: 0;

          &.active {
            color: #000;
            font-weight: bold;

            &::after {
              content: "";
              position: absolute;
              bottom: -20rpx;
              left: 50%;
              transform: translateX(-50%);
              width: 40rpx;
              height: 4rpx;
              background-color: #000;
              border-radius: 2rpx;
            }
          }
        }
      }
    }

    .category-nav-down {
      z-index: 99;
      position: fixed;
      right: 20rpx;
      top: 120rpx;
      height: 84rpx;
      padding: 0 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      /* #ifdef MP-WEIXIN */
      top: calc(var(--status-bar-height) + 120rpx + 106rpx);
      /* #endif */

      .category-nav-down-icon {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .scrollable-content {
    flex: 1;
    height: 0;

    .search-result {
      padding: 20rpx;

      .product-grid {
        column-count: 2;
        column-gap: 20rpx;
      }
    }
  }

  .category-popup {
    width: 100%;
    height: calc(100vh - 100rpx - 116rpx - var(--status-bar-height) + 110rpx);
    background-color: #fff;
    z-index: 98;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      border-bottom: 1rpx solid #f5f5f5;
      background: linear-gradient(to right, #fff, #fafafa);

      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .category-columns {
      display: flex;
      height: calc(100% - 86rpx);
      background-color: #fff;

      .category-column {
        flex: 1;
        position: relative;

        &::after {
          content: "";
          position: absolute;
          right: 0;
          top: 0;
          bottom: 0;
          width: 1rpx;
          background: linear-gradient(
            to bottom,
            transparent,
            #f0f0f0 10%,
            #f0f0f0 90%,
            transparent
          );
        }

        &:last-child::after {
          display: none;
        }

        .category-item {
          position: relative;
          padding: 32rpx 40rpx;
          font-size: 28rpx;
          color: #666;
          display: flex;
          align-items: center;
          transition: all 0.3s;

          &:active {
            background-color: #fafafa;
          }

          .count {
            margin-left: 8rpx;
            font-size: 24rpx;
            color: #999;
          }

          .arrow {
            position: absolute;
            right: 20rpx;
            color: #ccc;
            font-size: 32rpx;
          }

          &.active {
            color: #333;
            font-weight: 600;
            background-color: #f8f8f8;

            &::before {
              content: "";
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              width: 6rpx;
              height: 32rpx;
              background-color: #000;
              border-radius: 0 4rpx 4rpx 0;
            }
          }
        }
      }
    }
  }

  .loading {
    text-align: center;
    padding: 20rpx;
    color: #999;
    font-size: 24rpx;
  }
}
</style>
